package com.zd.certificate.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;

/**
 * 切换数据库类
 * @author hang.xu
 */
@Configuration
@Slf4j
public class SwitchDB {

    @Autowired
    DynamicDataSource dynamicDataSource;

    @Resource(name = "primaryProperties")
    PrimaryProperties primaryProperties;

    @Autowired
    private PlatformTransactionManager transactionManager;


    /**
     * 创建新的私有库数据源
     * @param ljyunId
     */
    public void  toYunDB(int userId){
        //组合私有库数据源对象key
        String dbSourceKey = "datasource-" + userId;
        //获取当前连接的数据源对象的key
        String currentKey = DataSourceContextHolder.get();
        if(dbSourceKey == currentKey) return;

        //创建私有库数据源
        createLjyunDataSource(userId);

        //切换到当前数据源
        DataSourceContextHolder.set(dbSourceKey);
        log.info("＝＝＝＝＝私有库: "+userId+",切换完毕");
    }

    /**
     * 创建私有库数据源，并将数据源赋值到targetDataSources中，供后切库用
     * @param ljyunId
     * @return
     */
    private HikariDataSource createLjyunDataSource(int userId){
        //创建新的数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(primaryProperties.getUrl());
        dataSource.setUsername(primaryProperties.getUsername());
        dataSource.setPassword(primaryProperties.getPassword());
        dataSource.setDriverClassName(primaryProperties.getDriverClassName());

        dynamicDataSource.setDataSource(userId , dataSource);
        return dataSource;
    }
}
